package com.fzsf.drawingboard.ui

import android.bluetooth.BluetoothDevice
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.fzsf.drawingboard.R
import com.fzsf.drawingboard.adapter.BlueDeviceAdapter
import com.fzsf.drawingboard.app.MyApplication
import com.fzsf.drawingboard.bluetooth.FZWritingPadConstant
import com.fzsf.drawingboard.bluetooth.FZWritingPadFactory
import com.fzsf.drawingboard.bluetooth.SimpleFZWritingPadCallBackListener
import com.fzsf.drawingboard.bluetooth.hypen.FZWritingPad_Hypen
import com.fzsf.drawingboard.bluetooth.iskn.FZWritingPad_ISKN
import com.fzsf.drawingboard.bluetooth.royole.FZWritingPad_RY
import com.fzsf.drawingboard.utils.BlueToothUtils
import com.fzsf.drawingboard.utils.ToastUtil
import com.kaopiz.kprogresshud.KProgressHUD
import kotlinx.android.synthetic.main.activity_connect.*

/**
 * 选择连接设备
 */
class ConnectActivity : AppCompatActivity() {
    private var mAdapter: BlueDeviceAdapter? = null
    private var listener: SimpleFZWritingPadCallBackListener = object : SimpleFZWritingPadCallBackListener() {
        override fun onConnectStateChange(currentSate: Int) {
            super.onConnectStateChange(currentSate)
            if (null != MyApplication.getInstance().writingPad && currentSate == FZWritingPadConstant.ConnectState.STATE_CONNECED) {
                MyApplication.getInstance().writingPad.switchWorkMode(FZWritingPadConstant.WorkMode.REAL_TIME)
                hideHud()
            }
        }

        override fun onWorkModeChange(currentWorkMde: Int) {
            super.onWorkModeChange(currentWorkMde)
            if (currentWorkMde == FZWritingPadConstant.WorkMode.REAL_TIME) {
                ToastUtil.showMessage("已经切换到实时模式，可返回书写页面书写")
                hideHud()
                finish()
            }
        }
    }

    private var progressHUD: KProgressHUD? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_connect)
        initView()
        startScanDevice()
    }

    private fun initView() {
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mAdapter = BlueDeviceAdapter(this)
        recyclerView.adapter = mAdapter
        mAdapter?.setOnItemDeviceClickListener { device -> connectDevice(device) }
    }

    private fun connectDevice(device: BluetoothDevice?) {
        showHud("正在连接...")
        if (null == device) {
            ToastUtil.showMessage("未知设备，请选择方正手写板")
            hideHud()
            return
        }
        val name = device.name
        when {
            BlueToothUtils.isHypenDevice(name) -> MyApplication.getInstance().writingPad = FZWritingPadFactory.getFZWritingPad(FZWritingPad_Hypen::class.java)
            BlueToothUtils.isRoyoleDevice(name) -> MyApplication.getInstance().writingPad = FZWritingPadFactory.getFZWritingPad(FZWritingPad_RY::class.java)
            BlueToothUtils.isIsknDevice(name) -> MyApplication.getInstance().writingPad = FZWritingPadFactory.getFZWritingPad(FZWritingPad_ISKN::class.java)
            else -> {
                ToastUtil.showMessage("未知设备，请选择方正手写板")
                hideHud()
            }
        }
        if (null != MyApplication.getInstance().writingPad) {
            BlueToothUtils.stopScan()
            MyApplication.getInstance().writingPad.setFZWritingPadCallBackListener(listener)
            MyApplication.getInstance().writingPad.connectDevice(device)
        }
    }

    /**
     * 开始扫描设备
     */
    private fun startScanDevice() {
        showScanning()
        BlueToothUtils.startScan(object : SimpleFZWritingPadCallBackListener() {
            override fun onDeviceFound(bluetoothDevice: BluetoothDevice) {
                super.onDeviceFound(bluetoothDevice)
                mAdapter?.addDevice(bluetoothDevice, 0)
            }

            override fun onLeScanEnd() {
                ToastUtil.showMessage("scan end!")
                showScanned()
            }
        })
    }

    private fun showScanning() {
        tv_choose_device.setText(R.string.scanning)
        pb_scaning.visibility = View.VISIBLE
    }

    private fun showScanned() {
        if (!isFinishing && !isDestroyed) {
            tv_choose_device.setText(R.string.scanned)
            pb_scaning.visibility = View.GONE
        }
    }

    private fun showHud(tips: String) {
        progressHUD = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel(tips)
                .setCancellable(true)
        progressHUD?.show()
    }

    private fun hideHud() {
        if (null != progressHUD && progressHUD!!.isShowing) {
            progressHUD!!.dismiss()
        }
    }

    override fun onBackPressed() {
        if (null != progressHUD && progressHUD!!.isShowing) {
            hideHud()
        } else {
            finish()
        }
    }
}
